<template>
  <div class="shopList">
    <headTop></headTop>
    <div class="shopTop">
      <el-table
        v-loading="loading"
        :header-cell-style="{ color: 'black', background: '#eef1f6' }"
        :data="tableData"
        style="width: 100%"
      >
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-form label-position="left" inline class="demo-table-expand">
              <el-form-item label="商品名称">
                <span>{{ props.row.name }}</span>
              </el-form-item>
              <el-form-item label="店铺地址">
                <span>{{ props.row.address }}</span>
              </el-form-item>
              <el-form-item label="店铺介绍">
                <span>{{ props.row.description }}</span>
              </el-form-item>
              <el-form-item label="店铺 ID">
                <span>{{ props.row.id }}</span>
              </el-form-item>
              <el-form-item label="联系电话">
                <span>{{ props.row.phone }}</span>
              </el-form-item>
              <el-form-item label="评分">
                <span>{{ props.row.rating }}</span>
              </el-form-item>
              <el-form-item label="销量">
                <span>{{ props.row.recent_order_num }}</span>
              </el-form-item>
              <el-form-item label="分类">
                <span>{{ props.row.category }}</span>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column label="店铺名称" prop="name"></el-table-column>
        <el-table-column label="店铺地址" prop="address"></el-table-column>
        <el-table-column label="店铺介绍" prop="description"></el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-button
              @click="handleEdit(scope.$index, scope.row)"
              size="mini"
              plain
              >编辑</el-button
            >
            <el-button
              @click="addFood(scope.$index, scope.row)"
              size="mini"
              plain
              >添加食品</el-button
            >
            <el-button
              @click="delted(scope.$index, scope.row)"
              size="mini"
              type="danger"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 15, 20, 25]"
        :page-size="limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="count"
      ></el-pagination>
    </div>
    <!-- 编辑 -->
    <el-dialog title="修改店铺信息" :visible.sync="dialogFormVisible">
      <el-form :model="selectTable">
        <el-form-item label="店铺名称" :label-width="formLabelWidth">
          <el-input v-model="selectTable.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="详细地址" :label-width="formLabelWidth">
          <el-input v-model="selectTable.address" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="店铺介绍" :label-width="formLabelWidth">
          <el-input
            v-model="selectTable.description"
            autocomplete="off"
          ></el-input>
          <span>当前城市:{{ city.name }}</span>
        </el-form-item>
        <el-form-item label="联系电话" :label-width="formLabelWidth">
          <el-input v-model="selectTable.phone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="店铺分类" :label-width="formLabelWidth">
          <el-cascader
            v-model="selectedCategory"
            :options="categoryOptions"
            @change="handleChange"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="商铺图片" :label-width="formLabelWidth">
          <el-upload
            class="avatar-uploader"
            :action="baseUrl + '/v1/addimg/shop'"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="selectTable.image_path"
              :src="baseImgPath + selectTable.image_path"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateShop">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import headTop from "../components/headTop";
import { baseUrl, baseImgPath } from "../config/env";
import {
  cityGuess,
  getResturants,
  getResturantsCount,
  foodCategory,
  updateResturant,
  searchplace,
  deleteResturant,
} from "../api/getData";
export default {
  data() {
    return {
      imageUrl: "",
      // 图片
      baseUrl,
      baseImgPath,
      tableData: [],
      // 城市定位
      city: {},
      // 每页条数
      limit: 10,
      // 跳过条数
      offset: 0,
      // 当前页数
      currentPage: 1,
      // 总数
      count: 0,
      // 加载
      loading: true,

      // 编辑
      dialogFormVisible: false,
      selectTable: {},
      formLabelWidth: "120px",
      // 级联选择器
      // 商铺种类
      selectedCategory: [],
      categoryOptions: [],
    };
  },
  created() {
    this.initData();
    console.log("baseUrl=====", this.baseUrl);
    console.log("baseImgPath====", this.baseImgPath);
  },
  components: {
    headTop,
  },
  methods: {
    async initData() {
      // 获取城市定位
      try {
        const { data } = await cityGuess();
        this.city = data;
        // 获取商铺数量
        const { data: date } = await getResturantsCount();

        if (date.status == 1) {
          this.count = date.count;
        } else {
          throw new Error("获取数据失败");
        }
        console.log("商铺数量====", date);
        this.getResturants();
      } catch (err) {
        console.log("获取数据失败", err);
      }
    },
    // 获取餐厅
    async getResturants() {
      const { latitude, longitude } = this.city;
      const { data } = await getResturants({
        latitude,
        longitude,
        limit: this.limit,
        offset: this.offset,
      });
      this.loading = false;
      console.log("商铺列表====", data);
      data.forEach((item) => {
        const tableData = {};
        tableData.name = item.name;
        tableData.address = item.address;
        tableData.description = item.description;
        tableData.id = item.id;
        tableData.phone = item.phone;
        tableData.rating = item.rating;
        tableData.recent_order_num = item.recent_order_num;
        tableData.category = item.category;
        tableData.image_path = item.image_path;
        this.tableData.push(tableData);
      });
    },

    // 获取食物种类
    async getCategory() {
      try {
        // 食物种类
        const { data } = await foodCategory();
        data.forEach((item) => {
          if (item.sub_categories.length) {
            const addnew = {
              value: item.name,
              label: item.name,
              children: [],
            };
            item.sub_categories.forEach((subitem, index) => {
              if (index == 0) {
                return;
              }
              addnew.children.push({
                value: subitem.name,
                label: subitem.name,
              });
            });
            this.categoryOptions.push(addnew);
          }
        });
        console.log("商品种类=====", data);
      } catch (err) {
        console.log("获取商铺种类失败", err);
      }
    },
    handleSizeChange(val) {
      this.limit = val;
      this.getResturants();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.offset = (val - 1) * this.limit;
      this.getResturants();
    },
    // 编辑
    handleEdit(index, row) {
      this.dialogFormVisible = true;
      this.selectTable = row;
      this.selectedCategory = row.category.split("/");
      if (!this.categoryOptions.length) {
        this.getCategory();
      }
    },
    handleChange(value) {
      console.log("==========", value);
    },
    //=========
    handleAvatarSuccess(res, file) {
      console.log("图片=====", res, file);
      if (res.status == 1) {
        this.selectTable.image_path = res.image_path;
      } else {
        this.$message.error("上传图片失败！");
      }
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    // 提交编辑
    async updateShop() {
      this.selectTable.category = this.selectedCategory.join("/");
      const res = await updateResturant(this.selectTable);
      console.log("提交编辑数据====", res);
      if (res.status == 1) {
        this.$message({
          type: "success",
          message: "更新店铺信息成功",
        });
        this.dialogFormVisible = false;
        //  获取餐厅
        this.getResturants();
      } else {
        this.$message({
          type: "error",
          message: res.message,
        });
      }
    },

    // 添加商品
    addFood(index, row) {
      console.log("添加商品==", row);
      this.$router.push({ path: "addGoods", query: { restaurantId: row.id } });
      // this.$router.push({ path: "addGoods", name:'addGoods', params: { restaurant_id: row.id } });
    },

    // 删除
   delted(index, row) {
      this.$confirm("确定要删除此数据吗", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then( async () => {
        const res = await deleteResturant(row.id)
        if(res.status == 1){
          this.$message({
            type:'success',
            message: '删除成功'
          })
          this.initData()
        } else {
          this.$message({
            type:'error',
            message: res.message
          })
        }
        console.log(res);
        console.log("删除", row);
      }).catch(()=>{
        console.log('取消删除');
      })
    },
  },
};
</script>

<style lang='less'>
.shopList {
  .shopTop {
    padding: 20px;
  }
}
.el-table {
  border: 1px solid #dfe6ec;
}
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
.el-button--mini {
  padding: 4px;
}
// 图片
.avatar-uploader {
  width: 120px;
  height: 120px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>